package cn.kbyue.security.security;

import cn.kbyue.security.utils.Env;
import java.util.Optional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.ProviderNotFoundException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;

/**
 * 自定义认证管理器
 *
 * @author xl
 * @date 2020/4/19 23:17
 */
@Slf4j
@Component
public class CustomAuthenticationManager implements AuthenticationManager {

    private final CustomAuthenticationProvider provider;

    public CustomAuthenticationManager(CustomAuthenticationProvider provider) {
        this.provider = provider;
    }

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {

        if (Env.isDebug) {
            log.info(">> AuthenticationManager authentication: {}", authentication);
        }

        Authentication authenticate = provider.authenticate(authentication);
        return Optional
                .ofNullable(authenticate)
                .orElseThrow(() -> new ProviderNotFoundException("Authentication failed!"));
    }
}
